package com.sina.mysql.utils;

import org.springframework.core.NamedInheritableThreadLocal;
import org.springframework.core.NamedThreadLocal;

/**
 * @ClassName UserContextHolder
 * @Description:
 * @Author 段浩杰
 * @Date 2018/8/22 17:48
 * @Version 1.0
 */
public abstract class UserContextHolder {

    private static final ThreadLocal<UserContext> USER_CONTEXT_HOLDER =
            new NamedThreadLocal<>( "UserContext" );

    private static final ThreadLocal<UserContext> INHERITABLE_USER_CONTEXT_HOLDER =
            new NamedInheritableThreadLocal<>( "UserContext" );


    /**
     * 清空当前线程的 holder
     */
    public static void reset() {
        USER_CONTEXT_HOLDER.remove();
        INHERITABLE_USER_CONTEXT_HOLDER.remove();
    }

    public static void set(UserContext userContext){
        set( userContext,false );
    }

    public static void set(UserContext userContext,boolean inheritable){
        if (inheritable) {
            INHERITABLE_USER_CONTEXT_HOLDER.set( userContext );
            USER_CONTEXT_HOLDER.remove();
        } else {
            USER_CONTEXT_HOLDER.set( userContext );
            INHERITABLE_USER_CONTEXT_HOLDER.remove();
        }
    }

    public static UserContext get(){
        UserContext context = USER_CONTEXT_HOLDER.get();
        if (context == null) {
            context = INHERITABLE_USER_CONTEXT_HOLDER.get();
        }
        return context;
    }

}